package com.lion.httpapi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.lion.httpapi.exception.UnkonwnMethodException;
/**
 * 请求NettyHttp服务
 * @author liyongyao
 *
 */
public class HttpClient {
	private String serverIP;
	private int serverPort;
	private String clientName;

	public HttpClient(String clientName, String serverIP, int serverPort) {
		this.serverIP = serverIP;
		this.serverPort = serverPort;
		this.clientName = clientName;
	}

	public String doPost(String path, String data, long timeOut,
			Map<String, String> params) throws Exception {
		return send(path, data, timeOut, "POST", params);
	}

	public String doPost(String path, String data,
			Map<String, String> params) throws Exception {
		return doPost(path, data, 60 * 1000, params);
	}

	public String doGet(String path, String data, long timeOut,
			Map<String, String> params) throws Exception {
		return send(path, data, timeOut, "GET", params);
	}

	public String doGet(String path, String data,
			Map<String, String> params) throws Exception {
		return doGet(path, data, 60 * 1000, params);
	}

	public String send(String path, String data, long timeOut,
			String method, Map<String, String> params) throws Exception {
		if (method.equals("POST") || method.equals("GET")) {
			BufferedReader reader = connServer(path, params, data, method, timeOut);
			return readInputStream(reader);
		} else {
			throw new UnkonwnMethodException("未知的请求类型：" + method);
		}
	}
	
	private String readInputStream(BufferedReader reader) throws Exception{
		StringBuilder result = new StringBuilder();
        String line = "";
        try{
        	while( (line = reader.readLine()) != null ){
        		result.append(line).append("\n");
        	}
        	return result.toString();
        }finally{
        	reader.close();
        }
    }

	private BufferedReader connServer(String path, Map<String, String> params,
			String data, String method, long timeOut) throws Exception {
		StringBuilder sendUrl = new StringBuilder();
		sendUrl.append("http://").append(this.serverIP).append(":")
				.append(this.serverPort).append(path);
		HttpURLConnection connection = null;
		OutputStream out = null;
		try {
			if (params == null) {
				params = new HashMap<String, String>();
			}
			connection = (HttpURLConnection) (new URL(sendUrl.toString())
					.openConnection());
			connection.setRequestMethod(method);
			connection.setUseCaches(false);
			connection.setDoOutput(true);
			connection.setRequestProperty("timeOut", String.valueOf(timeOut));
			connection.setRequestProperty("Content-type", "text/json");
			if (clientName != null) {
				connection.setRequestProperty("clientName", clientName);
			}
			if (!params.isEmpty()) {
				for (Entry<String, String> kv : params.entrySet()) {
					connection.addRequestProperty(kv.getKey(), kv.getValue());
				}
			}
			out = connection.getOutputStream();
			if(data!=null){
				out.write(data.getBytes());
			}
			out.flush();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					connection.getInputStream(), "UTF-8"));
			return in;
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
